import React, { useEffect, useRef } from 'react';

interface ComponentPreviewProps {
  schema: any;
  scale?: number;
  height?: number;
}

/**
 * 简单的 Schema 预览组件
 * 使用递归渲染将 lowcode schema 转换为 HTML
 */
const ComponentPreview: React.FC<ComponentPreviewProps> = ({
  schema,
  scale = 0.4,
  height = 400
}) => {
  const containerRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    if (!containerRef.current || !schema) {
      return;
    }

    // 递归渲染 schema 为 HTML
    const renderSchema = (schemaNode: any): string => {
      if (!schemaNode) return '';

      const componentName = schemaNode.componentName || 'div';
      const props = schemaNode.props || {};
      const children = schemaNode.children || [];

      // 处理样式
      let styleStr = '';
      if (props.style) {
        styleStr = Object.keys(props.style)
          .map(key => {
            // 将 camelCase 转换为 kebab-case
            const cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
            return `${cssKey}: ${props.style[key]}`;
          })
          .join('; ');
      }

      // 处理类名
      const className = props.className || '';

      // 根据组件类型渲染不同的 HTML
      let html = '';

      switch (componentName) {
        case 'Page':
        case 'FDPage':
        case 'Div':
        case 'FDBlock':
        case 'FDSection':
          html = `<div class="${className}" style="${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        case 'FDCell':
          html = `<div class="${className}" style="display: flex; flex-direction: column; ${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        case 'FDP':
          html = `<p class="${className}" style="margin: 8px 0; ${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </p>`;
          break;

        case 'NextText':
        case 'Text':
          const text = props.children || children[0] || '';
          html = `<span class="${className}" style="${styleStr}">${text}</span>`;
          break;

        case 'NextButton':
        case 'Button':
          const btnText = props.children || children[0] || '按钮';
          html = `<button class="${className}" style="padding: 8px 16px; border-radius: 4px; cursor: pointer; ${styleStr}">
            ${btnText}
          </button>`;
          break;

        case 'NextInput':
        case 'Input':
          const placeholder = props.placeholder || '';
          html = `<input placeholder="${placeholder}" class="${className}" style="padding: 8px; border: 1px solid #ddd; border-radius: 4px; ${styleStr}" />`;
          break;

        case 'NextBox':
        case 'Box':
          html = `<div class="${className}" style="padding: 16px; ${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        case 'NextBlockCell':
          html = `<div class="${className}" style="margin-bottom: 16px; ${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        case 'NextRowColContainer':
        case 'NextRow':
          html = `<div class="${className}" style="display: flex; flex-wrap: wrap; ${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        case 'NextCol':
          html = `<div class="${className}" style="flex: 1; padding: 8px; ${styleStr}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        case 'NextFormItem':
          const label = props.label || '';
          html = `<div class="${className}" style="margin-bottom: 16px; ${styleStr}">
            ${label ? `<label style="display: block; margin-bottom: 4px; font-weight: bold;">${label}</label>` : ''}
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
          break;

        default:
          // 默认渲染为 div
          html = `<div class="${className}" style="${styleStr}" data-component="${componentName}">
            ${children.map((child: any) => renderSchema(child)).join('')}
          </div>`;
      }

      return html;
    };

    // 渲染到容器
    const html = renderSchema(schema);
    const wrapper = document.createElement('div');
    wrapper.style.cssText = `
      width: 100%;
      height: 100%;
      background: #fff;
      overflow: auto;
      padding: 16px;
      box-sizing: border-box;
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
    `;
    wrapper.innerHTML = html;

    containerRef.current.innerHTML = '';
    containerRef.current.appendChild(wrapper);
  }, [schema, scale]);

  return (
    <div
      ref={containerRef}
      style={{
        height: `${height}px`,
        overflow: 'hidden',
        background: '#fff',
        border: '1px solid #e0e0e0',
        borderRadius: '4px',
        position: 'relative',
        transform: `scale(${scale})`,
        transformOrigin: 'top left',
        width: `${100 / scale}%`,
      }}
    />
  );
};

export default ComponentPreview;
